"""
JSON配置演示 - 展示Gua框架的可替换JSON支持
重构版本：基于Linus设计哲学，分离HTML/JavaScript
"简单、实用、零破坏性"
"""

import time
from gua import GuaApp, respond, create_websocket_manager, ws_json
from gua.template_utils import respond_template

# 创建应用实例 - 使用自动JSON选择
app = GuaApp()
ws_manager = create_websocket_manager()

@app.route("/")
async def home():
    """主页 - 显示当前JSON配置信息 - Linus式重构：使用模板"""
    json_info = app.config.json_info
    provider = json_info.get('provider', 'unknown')
    version = json_info.get('version', 'unknown')
    available = json_info.get('available', 'unknown')
    
    return respond_template("json_config.html", {
        "provider": provider,
        "version": version,
        "available": available
    })

@app.route("/api/auto")
async def auto_json():
    """自动JSON选择演示"""
    return respond({
        "message": "使用自动选择的JSON库",
        "config": app.config.json_info,
        "timestamp": time.time()
    })

@app.route("/api/performance")
async def performance_test():
    """性能测试API"""
    from gua.json_utils import json_dumps, get_json_info
    
    # 测试数据
    test_data = {
        "users": [{"id": i, "name": f"User {i}", "data": "x" * 100} for i in range(100)],
        "metadata": {"total": 100, "timestamp": "2024-01-01T00:00:00Z"}
    }
    
    # 性能测试
    start_time = time.time()
    for _ in range(100):
        json_str = json_dumps(test_data)
    end_time = time.time()
    
    return respond({
        "config": get_json_info(),
        "performance": {
            "operations": 100,
            "total_time": round(end_time - start_time, 4),
            "avg_time": round((end_time - start_time) / 100, 6),
            "data_size": len(json_str)
        },
        "test_data_size": len(test_data["users"])
    })

@app.route("/api/large-data")
async def large_data():
    """大数据处理演示"""
    # 生成大量数据
    large_data = {
        "records": [{"id": i, "value": f"data_{i}", "timestamp": time.time()} for i in range(1000)],
        "metadata": {
            "total": 1000,
            "generated_at": time.time(),
            "json_provider": app.config.json_info.get("provider", "unknown")
        }
    }
    
    return respond(large_data)

@app.websocket("/ws")
async def websocket_handler(scope, receive, send):
    """WebSocket处理器 - 实时性能监控"""
    from gua import ws_text
    await ws_text(send, "accept")
    ws_manager.add(send)
    
    try:
        while True:
            message = await receive()
            if message["type"] == "websocket.receive":
                if message.get("text") == "performance":
                    # 执行性能测试
                    from gua.json_utils import json_dumps
                    
                    test_data = {"data": "x" * 1000}
                    start_time = time.time()
                    for _ in range(50):
                        json_str = json_dumps(test_data)
                    end_time = time.time()
                    
                    await ws_json(send, {
                        "type": "performance",
                        "serialize_time": round((end_time - start_time) * 1000, 2),
                        "data_size": len(json_str),
                        "operations": 50,
                        "timestamp": time.time()
                    })
                else:
                    # 回显消息
                    await ws_json(send, {
                        "type": "echo",
                        "data": message.get("text", ""),
                        "timestamp": time.time()
                    })
    except Exception:
        pass
    finally:
        ws_manager.remove(send)

if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.json_config_demo:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.json_config_demo:app --example-info")